<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message, Tree } from 'ant-design-vue';

import { getDeptTreeApi, transferUserApi } from '#/api/core/user';
import { $t } from '#/locales';

const treeData = ref<any[]>([]);
const selectedKeys = ref<string[]>([]);
const loading = ref(false);
const expandedKeys = ref<string[]>([]);

// 加载组织树数据
const loadTreeData = async () => {
  try {
    const data = await getDeptTreeApi();
    if (Array.isArray(data)) {
      treeData.value = data;
      expandedKeys.value = data.length > 0 && data[0]?.key ? [data[0].key] : [];
    } else {
      message.error($t('user.transfer.treeDataError'));
    }
  } catch (error: any) {
    message.error($t('user.transfer.treeError'), error.message);
  }
};

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  async onConfirm() {
    if (selectedKeys.value.length === 0) {
      message.warning($t('user.transfer.selectTarget'));
      return false;
    }

    const targetDeptId = selectedKeys.value[0];
    if (!targetDeptId) {
      message.warning($t('user.transfer.invalidTarget'));
      return false;
    }
    const { currentDeptId, userId } = modalApi.getData<{
      currentDeptId: string;
      userId: string;
    }>();
    if (targetDeptId === currentDeptId) {
      message.warning($t('user.transfer.alreadyMember'));
      return false;
    }

    try {
      if (!userId) {
        throw new Error($t('user.transfer.userIdEmpty'));
      }
      await transferUserApi(userId, targetDeptId);
      message.success($t('user.transfer.success'));
      modalApi.close();
      return true;
    } catch (error: any) {
      message.error(error.message || $t('user.transfer.failed'));
      return false;
    }
  },
  onCancel() {
    selectedKeys.value = [];
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      loading.value = true;
      loadTreeData().finally(() => {
        loading.value = false;
      });
    } else {
      // 关闭时清理数据
      treeData.value = [];
      selectedKeys.value = [];
    }
  },
});
</script>

<template>
  <Modal
    :loading="loading"
    :title="$t('user.transfer.title')"
    class="w-[500px]"
  >
    <div v-if="loading" class="py-4 text-center">
      <span>{{ $t('user.transfer.loading') }}</span>
    </div>
    <Tree
      v-else
      v-model:expanded-keys="expandedKeys"
      v-model:selected-keys="selectedKeys"
      :field-names="{
        children: 'children',
        title: 'title',
        key: 'key',
      }"
      :tree-data="treeData"
    />
  </Modal>
</template>
